import React, { useEffect, useState, Fragment } from "react";
import {
  Button,
  Select,
  Table,
  Divider,
  message,
  Popconfirm,
  Form,
  Row,
  Col,
  Alert,
  Input
} from "antd";
import { connect } from "dva";
import styles from "./TemplateManager.less";
import { getList, updateStatus, deleteReceive } from "../services/acceptGroup";
import api from "../../../services/publicApi";
import ToggleColumns from "../../../components/toggleColumns";
import useMultiPageRowSelection from "../../../hooks/useMultiPageRowSelection";
import { getCurrentTenant } from "../../../utils/utils";

function TemplateManager(props) {
  const { history, form, userData } = props;
  const { getFieldDecorator, getFieldsValue, validateFields } = form;
  const [listData, setListData] = useState([]); // 表格数据
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [loading, setloading] = useState(false);
  const [showColumns, setShowColumns] = useState([]);
  const [columnCfg, setcolumnCfg] = useState({});
  const [
    selectedRowKeys,
    onSelectChange,
    resetRowSelection
  ] = useMultiPageRowSelection(listData, "id");

  const getMessageTemplateListData = () => {
    setloading(true);
    const params = {
      pageNum,
      pageSize,
      ...getFieldsValue()
    };
    getList(params).then(res => {
      if (res.success) {
        setListData(res.datas.list);
        setTotal(res.datas.total);
      } else {
        message.error(res.errMsg);
      }
      setloading(false);
    });
  };
  useEffect(() => {
    getMessageTemplateListData();
  }, [pageNum, pageSize]);

  const handleCommit = record => {
    window.console.log(record);
    const params = {
      // ...record,
      id: record.id,
      isEnabled: record.isEnabled === "Y" ? "N" : "Y"
    };
    const msg = record.isEnabled === "Y" ? "停用成功" : "启用成功";
    updateStatus(params).then(res => {
      if (res.success) {
        message.success(msg);
        getMessageTemplateListData();
      } else {
        message.error(res.errMsg);
      }
    });
  };
  const handleDelete = id => {
    deleteReceive({ id }).then(res => {
      if (res.success) {
        message.success("删除成功");
        getMessageTemplateListData();
      } else {
        message.error(res.errMsg);
      }
    });
  };

  const handlePageChange = page => {
    setPageNum(page);
  };
  const handlePageSizeChange = (current, size) => {
    setPageSize(size);
    setPageNum(1);
  };

  const handleSubmit = () => {
    validateFields(err => {
      if (!err) {
        resetRowSelection();
        getMessageTemplateListData();
      }
    });
  };

  const onReset = () => {
    form.resetFields();
    resetRowSelection();
    getMessageTemplateListData();
  };

  const originColumns = [
    {
      title: "序号",
      dataIndex: "id",
      width: 50,
      render: (a, b, c) => <span>{pageSize * (pageNum - 1) + c + 1}</span>
    },
    {
      title: "租户编码",
      dataIndex: "tenantCode"
    },
    {
      title: "租户名称",
      dataIndex: "tenantName"
    },
    {
      title: "接收组编码",
      dataIndex: "receiveGroupCode"
    },
    {
      title: "接收组名称",
      dataIndex: "receiveGroupName"
    },
    {
      title: "状态",
      dataIndex: "status"
    },
    {
      title: "接收组范围",
      dataIndex: "baseReceiveGroupRangeDTOList",
      ellipsis: true,
      render: ranges => {
        try {
          const arr = ranges || [];
          return arr
            .map(r =>
              JSON.parse(r.rangeEntityId)
                .map(obj => Object.values(obj)[0])
                .join(",")
            )
            .join(",");
        } catch (e) {
          const arr = ranges || [];
          return arr.map(r => r.rangeEntityId).join(",");
        }
      }
    },
    {
      title: "操作",
      dataIndex: "handle",
      width: 160,
      fixed: "right",
      render: (text, record) => {
        const isDisable = record.isEnabled === "Y";
        const offLineTitle =
          record.isEnabled === "Y" ? "确定停用接收组吗" : "确定启用接收组吗";
        return (
          <div>
            <a
              disabled={isDisable}
              onClick={() =>
                history.push(
                  `/messageCenter/AcceptGroup/list/AcceptAdd?id=${record.id}`
                )
              }
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="确定删除接收组吗"
              onConfirm={() => handleDelete(record.id)}
            >
              <a disabled={isDisable}>删除</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              title={offLineTitle}
              onConfirm={() => handleCommit(record)}
            >
              {record.isEnabled === "Y" ? (
                <a>停用</a>
              ) : (
                <a disabled={isDisable}>启用</a>
              )}
            </Popconfirm>
          </div>
        );
      }
    }
  ];

  useEffect(() => {
    const { userInfo = {} } = userData;
    if (!userInfo.userId) return;
    // 获取隐藏表格配置
    api
      .getColumnsByTable({ user: userInfo.userId, tag: "acceptGroup" })
      .then(res => {
        if (res.success) {
          setcolumnCfg(res.datas[0] || {});
          if (res.datas.length === 0 || res.datas[0].config === "") {
            setShowColumns(originColumns);
          } else {
            const hiddenArr = res.datas[0].config.split(",");
            setShowColumns(
              originColumns.filter(
                c => !hiddenArr.find(hc => hc === c.dataIndex)
              )
            );
          }
        } else {
          message.error(res.errMsg);
        }
      });
  }, [userData]);

  const onSetColumns = (shows, hiddens) => {
    const { userInfo = {} } = userData;
    setShowColumns(shows);
    // 同步动态表格隐藏列信息
    api
      .updateColumnsByTable({
        config: hiddens.map(h => h.dataIndex).join(","),
        user: userInfo.userId,
        tag: columnCfg.tag || "acceptGroup",
        id: columnCfg.id
      })
      .then(res => {
        if (!res.success) {
          message.warning("动态表格同步失败");
        }
      });
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 }
    }
  };
  return (
    <div className={styles.root}>
      <div className={styles.titleBox}>接收组列表</div>
      <div className={styles.topSearch}>
        <div className={styles.rightSearch}>
          <Form {...formItemLayout}>
            <Row>
              <Col span={6}>
                <Form.Item label="接收组名称">
                  {getFieldDecorator("receiveGroupName")(
                    <Input placeholder="请输入" />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="接收组编码">
                  {getFieldDecorator("receiveGroupCode")(
                    <Input placeholder="请输入" />
                  )}
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label="状态">
                  {getFieldDecorator("isEnabled")(
                    <Select placeholder="请选择" allowClear>
                      <Select.Option value="Y">启用</Select.Option>
                      <Select.Option value="N">停用</Select.Option>
                    </Select>
                  )}
                </Form.Item>
              </Col>
              <Col span={6} style={{ textAlign: "right" }}>
                <Button style={{ marginRight: "10px" }} onClick={onReset}>
                  重置
                </Button>
                <Button type="primary" onClick={handleSubmit}>
                  搜索
                </Button>
              </Col>
            </Row>
          </Form>
          {/* <RangePicker
            style={{ width: 224, marginRight: 24 }}
            onChange={handleDateChange}
          />
          <Input
            style={{ width: 224, marginRight: 24 }}
            placeholder="请输入接收组名称"
            onChange={handleSearch}
          />
          <Button type="primary" onClick={() => onSearch()}>
            查询
          </Button> */}
        </div>
      </div>
      <div className={styles.tableBox}>
        <div className={styles.tableTopBox}>
          <div>
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={() => {
                window.open(
                  `/mgt/excel/outputReceptGroupExcel?param=${selectedRowKeys.join(
                    ","
                  )}`,
                  "_blank"
                );
              }}
              disabled={selectedRowKeys.length === 0}
            >
              批量导出
            </Button>
            {selectedRowKeys.length !== 0 && (
              <Fragment>
                <Alert
                  style={{
                    display: "inline-block",
                    padding: "5px 8px",
                    marginLeft: 10
                  }}
                  message={`已选中 ${selectedRowKeys.length} 条记录`}
                  type="info"
                />
              </Fragment>
            )}
          </div>
          <div>
            <ToggleColumns
              originColumns={originColumns}
              showColumns={showColumns}
              onSetColumns={onSetColumns}
            />
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              onClick={() =>
                history.push("/messageCenter/AcceptGroup/list/AcceptAdd")
              }
              disabled={getCurrentTenant().id === '100000'}
            >
              新建接收组
            </Button>
          </div>
        </div>
        <Table
          dataSource={listData}
          columns={showColumns}
          rowKey="id"
          scroll={{ x: "max-content" }}
          loading={loading}
          rowSelection={{ selectedRowKeys, onChange: onSelectChange }}
          // onChange={handleFilter}
          pagination={{
            current: pageNum,
            pageSize,
            showSizeChanger: true,
            showQuickJumper: true,
            total,
            onChange: handlePageChange,
            onShowSizeChange: handlePageSizeChange,
            showTotal: () => `共有${total}条`
          }}
        />
      </div>
    </div>
  );
}

export default connect(stores => ({
  userData: stores.user
}))(Form.create()(TemplateManager));
